package com.xy.biz.base.manager.impl;

import com.xy.biz.base.dao.UnitConvertDao;
import com.xy.biz.base.domain.po.UnitConvertPO;
import com.xy.biz.base.manager.UnitConvertManager;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class UnitConvertManagerImpl implements UnitConvertManager, InitializingBean {

    @Autowired
    private UnitConvertDao unitConvertDao;

    private List<UnitConvertPO> cache;

    @Override
    public void afterPropertiesSet() throws Exception {
        cache = unitConvertDao.listUnitConvert();
        if(cache == null) {
            cache = new ArrayList<>();
        }
    }

    @Override
    public Map<String, Map<String, Integer>> mapUnitConvert() {
        List<UnitConvertPO> unitConvertPOList = cache;
        if(CollectionUtils.isEmpty(unitConvertPOList)) {
            return Collections.EMPTY_MAP;
        }

        Map<String, Map<String, Integer>> topMap = new HashMap<>();
        for(UnitConvertPO unitConvertPO : unitConvertPOList) {
            Map<String, Integer> map = topMap.computeIfAbsent(unitConvertPO.getConverteeUnit(), (key) -> new HashMap<>());
            map.put(unitConvertPO.getConverterUnit(), unitConvertPO.getMultiplier());
        }
        return topMap;
    }

}
